import { useUserStore } from "@/store/user";
import { useMenuStore } from "@/store/menus";
import { notification } from "@/hooks/modules/useToast";
import { Request } from "@/services/request";
import { removeCookieToken } from "@/utils/cookies";

type ErrorNotificationType = "NoMenus" | "abnormal";

export const usePermissions = () => {
  const { setUserInfo, setAuthPermission, setAuthRole, clearUserInfo } = useUserStore.getState();

  const { setAuthMenuList, clearAuthMenu } = useMenuStore.getState();

  const checkErrorNotification = (reason: ErrorNotificationType) => {
    const notificationMap: Record<string, string> = {
      NoMenus: "当前账号未获取到菜单信息，请联系系统管理员！",
      abnormal: "当前账号获取菜单或角色接口出现异常，请联系系统管理员！"
    };

    notification.warning({
      message: "无权限访问",
      description: notificationMap[reason]
    });
    removeCookieToken();
    clearUserInfo();
    clearAuthMenu();
  };

  const initPermissions = async (token: string) => {
    if (!token) return;
    try {
      const { data: userInfo } = (await Request.get("/user")) as unknown as Record<string, any>;
      setUserInfo(userInfo);
      setAuthPermission(userInfo);
      setAuthRole(userInfo);

      const { data: authMenuList } = (await Request.get("/menus")) as unknown as Record<string, any>;
      setAuthMenuList(authMenuList);

      if (!authMenuList.length) {
        checkErrorNotification("NoMenus");
        return Promise.reject("当前账号未获取到菜单信息，请联系系统管理员！");
      }
    } catch (e) {
      checkErrorNotification("abnormal");
      return Promise.reject("当前账号获取菜单或角色接口出现异常，请联系系统管理员！");
    }
  };

  return { initPermissions };
};
